from django.core.management.base import BaseCommand
from movies.models import Movie
import requests
import time

class Command(BaseCommand):
    help = '使用TMDB API更新电影海报和详情'

    def add_arguments(self, parser):
        parser.add_argument('--api_key', type=str, required=True, help='TMDB API密钥')

    def handle(self, *args, **options):
        api_key = options['api_key']
        
        # 获取所有没有海报的电影
        movies = Movie.objects.filter(poster_url__isnull=True) | Movie.objects.filter(poster_url__exact='')
        
        for movie in movies:
            self.update_movie_poster(movie, api_key)
            # 避免API请求过于频繁
            time.sleep(0.5)
        
        self.stdout.write(self.style.SUCCESS('所有海报更新完成!'))
    
    def update_movie_poster(self, movie, api_key):
        """使用TMDB API更新电影海报"""
        search_url = f"https://api.themoviedb.org/3/search/movie?api_key={api_key}&query={movie.title}&year={movie.year}&language=zh-CN"
        
        try:
            response = requests.get(search_url)
            data = response.json()
            
            if 'results' in data and data['results']:
                # 取搜索结果的第一个
                movie_data = data['results'][0]
                
                if movie_data.get('poster_path'):
                    movie.poster_url = f"https://image.tmdb.org/t/p/w500{movie_data['poster_path']}"
                
                if movie_data.get('backdrop_path'):
                    movie.backdrop_url = f"https://image.tmdb.org/t/p/original{movie_data['backdrop_path']}"
                
                if movie_data.get('overview'):
                    movie.description = movie_data['overview']
                
                movie.tmdb_id = movie_data['id']
                movie.popularity = movie_data.get('popularity', 0)
                movie.vote_average = movie_data.get('vote_average', 0)
                movie.vote_count = movie_data.get('vote_count', 0)
                
                # 获取更详细信息
                details_url = f"https://api.themoviedb.org/3/movie/{movie.tmdb_id}?api_key={api_key}&language=zh-CN"
                details_response = requests.get(details_url)
                details_data = details_response.json()
                
                if 'runtime' in details_data:
                    movie.runtime = details_data['runtime']
                
                if 'imdb_id' in details_data:
                    movie.imdb_id = details_data['imdb_id']
                
                movie.save()
                self.stdout.write(f"更新了电影 '{movie.title}'的海报和详情")
            else:
                self.stdout.write(self.style.WARNING(f"没有找到电影 '{movie.title}'的信息"))
        
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"更新电影 '{movie.title}'时出错: {str(e)}")) 